package com.licheedev.glide_qrcode;

import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.data.DataFetcher;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

/**
 * 使用Glide加载二维码，方便复用生成的bitmap
 */
class QrCodeFetcher implements DataFetcher<ByteBuffer> {

    private final QrCode mQrCode;

    public QrCodeFetcher(QrCode qrCode) {
        mQrCode = qrCode;
    }

    @Override
    public void loadData(@NonNull Priority priority,
        @NonNull final DataCallback<? super ByteBuffer> callback) {

        new Thread() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = QRCodeUtil.loadQrCode(mQrCode);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    if (bitmap != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    }
                    callback.onDataReady(ByteBuffer.wrap(baos.toByteArray()));
                } catch (Exception e) {
                    callback.onLoadFailed(e);
                }
            }
        }.start();
    }

    @Override
    public void cleanup() {

    }

    @Override
    public void cancel() {

    }

    @NonNull
    @Override
    public Class<ByteBuffer> getDataClass() {
        return ByteBuffer.class;
    }

    @NonNull
    @Override
    public DataSource getDataSource() {
        return DataSource.REMOTE;
    }
}
